﻿#include "skinmgr.h"
#include <QWidget>
#include <QFile>
#include "skin.h"
#include <QApplication>
#include <QScreen>
//#include <QtCore5Compat>
#include <QString>

static double scale_dip()
{
    static double dip = QApplication::primaryScreen()->logicalDotsPerInch() / 96.0f;
    return dip;
}
#if 1  //T_NO_DEBUG
QssFile  g_qss[] = {
    {SK_Main, ":/titlebar/qss/Main.css"},
    {SK_PLAYER,":/titlebar/qss/player.css"}
};
#else
QssFile  g_qss[] = {
    {SK_SVip, "F:/WorkSpace/Cpp/Modules/VipFrame/trunk/VipFrame/rc/qss/svipdialog.css"},
    {SK_Login, "F:/WorkSpace/Cpp/Modules/VipFrame/trunk/VipFrame/rc/qss/logindialog.css"},
    {SK_User, "F:/WorkSpace/Cpp/Modules/VipFrame/trunk/VipFrame/rc/qss/userdialog.css"},
    {SK_Update, "F:/WorkSpace/Cpp/Modules/VipFrame/trunk/VipFrame/rc/qss/updatedialog.css"},
    };
#endif


SkinMgr::SkinMgr(QObject *parent)
    : QObject(parent)
{

}

void SkinMgr::setSkin(SkinId id, QWidget *w)
{
    QString style = loadQss(g_qss[id].name);
    w->setStyleSheet(style);
}

QString SkinMgr::loadQss(QString qssFile)
{
    QString resultQss = "";
    double dip  = scale_dip();

    QFile file(qssFile);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return "";
    }

    if(dip == 1.0) {
        resultQss = QString::fromUtf8(file.readAll().data());
    } else {
        while (!file.atEnd())
        {
            QByteArray text = file.readLine();
            if(dip != 1.0) {
                resultQss += dealLine(QString::fromUtf8(text.data()), dip);
            }
        }
    }
    file.close();
    return resultQss;
}

QString SkinMgr::dealLine(const QString &lineText, qreal dip)
{
    QString line = lineText;
    QRegExp reg("[0-9]{1,4}px");
    int start = 0;
    do {
        int idx =  line.indexOf(reg, start);
        if(idx == -1) break;
        int end = line.indexOf("px", idx);
        QString text = line.mid(idx, end-idx);
        QString rtext = QString::number((int)(text.toInt() *  dip));
        line.replace(idx, end-idx, rtext);
        start = idx + rtext.length() + 2;

    }while (1);
    return line;
}
